package com.cqs.leetcode.sort;

import java.util.*;

/**
 * @author lixiaowen
 * @create 2019-12-12
 */
public class TopKFrequentWords692 {

    public List<String> topKFrequent(String[] words, int k) {
        //Map<String,Long> map = Arrays.stream(words).collect(Collectors.groupingBy(t -> t, Collectors.counting()));//比较耗性能
        Map<String,Integer> map = new HashMap<>(words.length * 2);
        for (String word : words) {
            map.put(word,1 + map.getOrDefault(word,0));
        }

        Comparator<Map.Entry<String,Integer>> comparator = (o1, o2) -> {
            int diff = (o2.getValue() - o1.getValue());
            if (diff != 0){
                return diff;
            }
            return o1.getKey().compareTo(o2.getKey());
        };
        PriorityQueue<Map.Entry<String,Integer>> queue = new PriorityQueue<>(map.size(),comparator);
        queue.addAll(map.entrySet());
        List<String> list = new ArrayList<>(k);
        for (int i = 0; i < k; i++) {
            list.add(queue.poll().getKey());
        }
        return list;
    }

    public static void main(String[] args) {
        int n = 100;
        String[] words =new String[n];
        for (int i = 0; i < 100; i++) {
            words[i] = String.valueOf(new Random().nextInt(n/10));
        }
        List<String> list = new TopKFrequentWords692().topKFrequent(words, 5);
        System.out.println(list);
        System.out.println("i".compareTo("love"));
        Queue queue  = null;

        queue.offer(null);

    }
}
